package com.yunwaikeji.gy_tool_library.widget.recycler.image;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;

import com.yunwaikeji.gy_tool_library.R;
import com.yunwaikeji.gy_tool_library.adapter.recycler.GYRecyclerAdapter;
import com.yunwaikeji.gy_tool_library.adapter.recycler.GYViewHolder;
import com.yunwaikeji.gy_tool_library.base.GYBaseUtils;
import com.yunwaikeji.gy_tool_library.info.GYBaseInfo;
import com.yunwaikeji.gy_tool_library.info.GYImageRecyclerInfo;
import com.yunwaikeji.gy_tool_library.utils.GYUiUtils;
import com.yunwaikeji.gy_tool_library.utils.GYUtils;
import com.yunwaikeji.gy_tool_library.utils.GYViewUtils;
import com.yunwaikeji.gy_tool_library.utils.display.GYDisplayUtils;
import com.yunwaikeji.gy_tool_library.utils.file.GYFileLoadListener;
import com.yunwaikeji.gy_tool_library.utils.http.GYHttpUtils;
import com.yunwaikeji.gy_tool_library.utils.http.upload.GYUploadModel;

import com.yunwaikeji.gy_tool_library.utils.picture.download.GYCompletedListener;
import com.yunwaikeji.gy_tool_library.utils.picture.download.GYErrorListener;
import com.yunwaikeji.gy_tool_library.utils.picture.download.GYFinishListener;
import com.yunwaikeji.gy_tool_library.utils.picture.download.GYLoadListener;
import com.yunwaikeji.gy_tool_library.utils.picture.download.GYPictureDownload;
import com.yunwaikeji.gy_tool_library.view.GYImageView;
import com.yunwaikeji.gy_tool_library.view.GYRelativeLayout;

import java.io.File;

public class GYImageRecyclerAdapter extends GYRecyclerAdapter<GYImageRecyclerModel, GYViewHolder> implements GYImageRecyclerInfo {
    private final Context context;
    private final GYImageRecyclerView imageRecyclerView;

    public GYImageRecyclerAdapter(GYImageRecyclerView imageRecyclerView) {
        super(R.layout.adapter_gy_image);
        this.context = imageRecyclerView.getContext();
        this.imageRecyclerView = imageRecyclerView;
        addChildClickViewIds(R.id.delImg);
    }

    @Override
    protected void convert(GYViewHolder holder, GYImageRecyclerModel model) {
        GYRelativeLayout itemLl = holder.getView(R.id.itemRl);
        ImageView imageView = holder.getView(R.id.gyImg);
        TextView progressTv = holder.getView(R.id.progressTv);
        GYImageView deleteImg = holder.getView(R.id.delImg);
        PathType pathType = model.getPathType();

        if (imageRecyclerView.getImageRecyclerBuilder().getItemWidthPx() != GYBaseInfo.WRAP_CONTENT && imageRecyclerView.getImageRecyclerBuilder().getItemHeightPx() != GYBaseInfo.WRAP_CONTENT) {
            itemLl.getViewSet().setSizePx(imageRecyclerView.getImageRecyclerBuilder().getItemWidthPx(), imageRecyclerView.getImageRecyclerBuilder().getItemHeightPx());
        }

        ConstraintSet constraintSet = new ConstraintSet();
        if (!TextUtils.isEmpty(imageRecyclerView.getImageRecyclerBuilder().getItemProportion()) && imageRecyclerView.getImageRecyclerBuilder().getItemProportion().contains(":")) {
            String[] strings = imageRecyclerView.getImageRecyclerBuilder().getItemProportion().split(":");
            if (strings.length == 2) {
                if (GYUtils.isNumber(strings[0]) && GYUtils.isNumber(strings[1])) {
                    constraintSet.setDimensionRatio(imageView.getId(), imageRecyclerView.getImageRecyclerBuilder().getItemProportion());
                }
            }
        } else {
            if (imageRecyclerView.getRecyclerBuilder().getRecyclerDisplayStyle() == DisplayStyle.GRID) {
                constraintSet.setDimensionRatio(imageView.getId(), "1:1");
            }
        }

        Boolean isEdit = model.isEdit();
        if (isEdit == null) {
            isEdit = imageRecyclerView.getImageRecyclerBuilder().isEdit();
        }

        if (model.getPathType() == PathType.ADD) {
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            GYViewUtils.setSize().setSizePx(imageView, Math.round(imageRecyclerView.getImageRecyclerBuilder().getAddDrawableWidth()), Math.round(imageRecyclerView.getImageRecyclerBuilder().getAddDrawableHeight()));
            if (imageRecyclerView.getImageRecyclerBuilder().getAddDrawable() == null) {
                imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.gylibrary_add));
            } else {
                imageView.setImageDrawable(imageRecyclerView.getImageRecyclerBuilder().getAddDrawable());
            }
            deleteImg.setVisibility(View.GONE);
            itemLl.getBackgroundBuilder()
                    .setEdgeWidthPx(Math.round(imageRecyclerView.getImageRecyclerBuilder().getAddEdgeWidth()))
                    .setEdgeColor(imageRecyclerView.getImageRecyclerBuilder().getAddEdgeColor())
                    .setEdgeOver(imageRecyclerView.getImageRecyclerBuilder().isAddEdgeOver())
                    .build();
        } else {
            imageView.setScaleType(imageRecyclerView.getImageRecyclerBuilder().getScaleType());
            GYViewUtils.setSize().setSizePx(imageView, GYBaseInfo.MATCH_PARENT, GYBaseInfo.MATCH_PARENT);
            if (isEdit) {
                deleteImg.setVisibility(View.VISIBLE);
                if (imageRecyclerView.getImageRecyclerBuilder().getDeleteDrawable() == null) {
                    deleteImg.getImageBuilder().setImageResource(R.drawable.gylibrary_delete).build();
                } else {
                    deleteImg.getImageBuilder().setImageDrawable(imageRecyclerView.getImageRecyclerBuilder().getDeleteDrawable()).build();
                }
                deleteImg.getViewSet().setSizePx(imageRecyclerView.getImageRecyclerBuilder().getDeleteDrawableWidthPx(), imageRecyclerView.getImageRecyclerBuilder().getDeleteDrawableHeightPx());
                ConstraintLayout.LayoutParams layoutParams1 = (ConstraintLayout.LayoutParams) deleteImg.getLayoutParams();
                layoutParams1.setMargins(imageRecyclerView.getImageRecyclerBuilder().getDeleteDrawableMarginLeftPx(), imageRecyclerView.getImageRecyclerBuilder().getDeleteDrawableMarginTopPx(), imageRecyclerView.getImageRecyclerBuilder().getDeleteDrawableMarginRightPx(), imageRecyclerView.getImageRecyclerBuilder().getDeleteDrawableMarginBottomPx());
                switch (imageRecyclerView.getImageRecyclerBuilder().getDeleteLocation()) {
                    case DeleteLocation.LEFT_TOP:
                        layoutParams1.leftToLeft = 0;
                        layoutParams1.topToTop = 0;
                        break;
                    case DeleteLocation.RIGHT_TOP:
                        layoutParams1.rightToRight = 0;
                        layoutParams1.topToTop = 0;
                        break;
                    case DeleteLocation.RIGHT_BOTTOM:
                        layoutParams1.rightToRight = 0;
                        layoutParams1.bottomToBottom = 0;
                        break;
                    case DeleteLocation.LEFT_BOTTOM:
                        layoutParams1.leftToLeft = 0;
                        layoutParams1.bottomToBottom = 0;
                        break;
                }
                deleteImg.setLayoutParams(layoutParams1);
            } else {
                deleteImg.setVisibility(View.GONE);
            }
        }

        itemLl.getBackgroundBuilder()
                .setEdgeWidthPx(Math.round(imageRecyclerView.getImageRecyclerBuilder().getImageEdgeWidth()))
                .setEdgeColor(imageRecyclerView.getImageRecyclerBuilder().getImageEdgeColor())
                .setEdgeOver(imageRecyclerView.getImageRecyclerBuilder().isImageEdgeOver())
                .build();

        if (pathType == null) {
            if (GYUtils.isNumber(model.getLoadPath())) {
                pathType = PathType.RESOURCE;
            } else if (TextUtils.isEmpty(model.getLoadPath()) || (model.getLoadPath().length() >= 4 && model.getLoadPath().startsWith("http"))) {
                pathType = PathType.NETWORK;
            } else {
                pathType = PathType.LOCAL;
            }
        }
        if (pathType != PathType.ADD) {
            if (TextUtils.isEmpty(model.getLocalPath())) {
                showLong(progressTv, "加载中");
            }
            model.setState(State.DOWNLOAD);
            switch (pathType) {
                case RESOURCE:
                    String path = GYBaseUtils.getCacheDirectory().getPath();
                    String name = model.getLoadPath() + ".png";
                    File file = new File(path, name);
                    if (!file.exists()) {
                        Drawable drawable = context.getResources().getDrawable(Integer.parseInt(model.getLoadPath()));
                        if (drawable == null) {
                            showLong(progressTv, "不存在");
                        } else {
                            GYDisplayUtils.saveToSD(GYDisplayUtils.toBitmap(drawable), path, name);
                        }
                    }
                    if (file.exists()) {
                        GYPictureDownload.with(context).load(file).into(imageView);
                        model.setLocalPath(file.getPath());
                    }
                    model.setState(State.NORMAL);
                    dismissTip(progressTv);
                    if (model.isToUpload()) {
                        itemChange(holder.getItemPosition());
                    }
                    break;
                case NETWORK:
                    GYPictureDownload.with(context)
                            .load(model.getLoadPath())
                            .setStartDrawable(imageRecyclerView.getImageRecyclerBuilder().getStartDrawable())
                            .setLoadingDrawable(imageRecyclerView.getImageRecyclerBuilder().getLoadingDrawable())
                            .setErrorDrawable(imageRecyclerView.getImageRecyclerBuilder().getErrorDrawable())
                            .setLoadListener(new GYLoadListener() {
                                @Override
                                public void loading(long nowBytes, long totalBytes, long secondBytes) {
                                    if (imageRecyclerView.getImageRecyclerBuilder().isProgressShow()) {
                                        showLong(progressTv, "加载中\n" + (nowBytes * 100 / totalBytes) + "%");
                                    }
                                }
                            })
                            .setCompletedListener(new GYCompletedListener() {
                                @Override
                                public void completed(File downFile, File cacheFile) {
                                    progressTv.setVisibility(View.GONE);
//                                    showTip(progressTv, "加载完成", 1000);
                                    if (model.isToUpload()) {
                                        itemChange(holder.getItemPosition());
                                    }
                                }
                            })
                            .setErrorListener(new GYErrorListener() {
                                @Override
                                public void error(String error) {
                                    showLong(progressTv, error);
                                }
                            })
                            .setFinishListener(new GYFinishListener() {
                                @Override
                                public void finish() {
                                    model.setState(State.NORMAL);
                                }
                            })
                            .into(imageView);
                    break;
                case LOCAL:
                    file = new File(model.getLoadPath());
                    if (!file.exists()) {
                        showLong(progressTv, "不存在");
                    } else {
                        imageView.setImageBitmap(GYDisplayUtils.getBitmap(model.getLoadPath()));
                        model.setLocalPath(model.getLoadPath());
                    }
                    model.setState(State.NORMAL);
                    dismissTip(progressTv);
                    if (model.isToUpload()) {
                        itemChange(holder.getItemPosition());
                    }
                default:
                    break;
            }
            if (model.getState() == State.NORMAL
                    && model.isToUpload()
                    && !TextUtils.isEmpty(model.getLocalPath())
                    && TextUtils.isEmpty(model.getUrl())) {
                if (!new File(model.getLocalPath()).exists()) {
                    showError(progressTv, "图片不存在");
                    return;
                }
                GYUploadModel<?> uploadModel = model.getUploadModel();
                if (uploadModel == null) {
                    uploadModel = imageRecyclerView.getImageUploadBuilder().getUploadModel();
                }
                if (uploadModel == null) {
                    showLong(progressTv, "无接口");
                    return;
                }
                uploadModel.setFile(model.getLocalPath());
                GYHttpUtils.newUploadTask()
                        .setHttpModel(uploadModel)
                        .setFileLoadListener(new GYFileLoadListener() {
                            @Override
                            public void paused() {

                            }

                            @Override
                            public void loading(long nowBytes, long totalBytes, long secondBytes) {
                                showLong(progressTv, "上传中\n" + (nowBytes * 100 / totalBytes) + "%");
                            }

                            @Override
                            public void success(String s) {
                                model.setUrl(s);
                                model.setToUpload(false);
                                showSuccess(progressTv, "上传成功");
                            }

                            @Override
                            public void start() {
                                imageRecyclerView.getImageUploadBuilder().setNowNumber(imageRecyclerView.getImageUploadBuilder().getNowNumber() + 1);
                                model.setState(State.UPLOADING);
                                showLong(progressTv, "准备上传");
                            }

                            @Override
                            public void stop() {

                            }

                            @Override
                            public void error(String error) {
                                showLong(progressTv, "上传失败");
                            }

                            @Override
                            public void finish() {
                                imageRecyclerView.getImageUploadBuilder().setNowNumber(imageRecyclerView.getImageUploadBuilder().getNowNumber() - 1);
                                model.setState(State.NORMAL);
                                if (imageRecyclerView.getOnItemChangeListener() != null) {
                                    imageRecyclerView.getOnItemChangeListener().onItemChange();
                                }
                            }
                        })
                        .start();
            }
        }
    }

    private void showTip(TextView textView, String tipString, long showTime) {
        if (showTime < 0) {
            textView.setVisibility(View.VISIBLE);
        } else if (showTime == 0) {
            textView.setVisibility(View.GONE);
        } else {
            textView.setVisibility(View.VISIBLE);
            GYUiUtils.getMainHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    textView.setVisibility(View.GONE);
                }
            }, showTime);
        }
        textView.setText(tipString);
    }

    private void showLong(TextView textView, String tipString) {
        showTip(textView, tipString, -1);
    }

    private void showSuccess(TextView textView, String tipString) {
        showTip(textView, tipString, 2000);
    }

    private void showError(TextView textView, String tipString) {
        showTip(textView, tipString, 2000);
    }

    private void dismissTip(TextView textView) {
        textView.setVisibility(View.GONE);
    }

    private void itemChange(int position) {
        GYUiUtils.runOnUiThread(() -> {
//            notifyItemChanged(position);
        });
    }
}
